// 导入外部模块 - 浏览器环境兼容
let axios = null;
let https = null;

// 环境检测和模块加载
if (typeof window !== 'undefined') {
    // 浏览器环境
    console.log('检测到浏览器环境，使用fetch API替代axios');
    // 在浏览器中使用fetch API替代axios
    axios = {
        post: async function(url, data, config = {}) {
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    mode: 'cors', // 明确设置CORS模式
                    headers: {
                        'Content-Type': 'application/json',
                        ...config.headers
                    },
                    body: JSON.stringify(data)
                });
                
                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const responseText = await response.text();
                return {
                    status: response.status,
                    data: responseText
                };
            } catch (error) {
                console.error('Fetch请求失败:', error);
                // 抛出带有更多信息的错误
                const fetchError = new Error(`Fetch请求失败: ${error.message}`);
                fetchError.request = true; // 标记为请求错误
                throw fetchError;
            }
        }
    };
} else {
    // Node.js环境
    try {
        const { customRequire } = require('./utils.js');
        axios = customRequire('axios');
        https = require('https');
        
        // 验证axios是否正确加载
        if (!axios || typeof axios.post !== 'function') {
            console.log('通过customRequire加载的axios无效或不包含post方法，尝试直接导入');
            try {
                axios = require('axios');
            } catch (err) {
                console.error('直接导入axios也失败:', err.message);
            }
        }
    } catch (err) {
        console.warn('Node.js环境模块加载失败:', err.message);
    }
}

const url = 'https://api.powerbi.com/beta/e96fa72b-c8d6-4957-96bd-c7f8dc30cc88/datasets/31fb02b8-3e95-4bec-b9b2-5af9c0d67aa0/rows?experience=power-bi&key=28Ri5RxnC5wvZFax5umuUDI2FZi6LxZ6q1bZPLqtfNfSXkLIuxqvge6bkETamwjdYIo%2F0EP8sgoAVzi55wI2Dw%3D%3D';

// 使用Node.js内置https模块发送请求的备用方法
async function sendWithNodeHttps(data) {
    if (typeof window !== 'undefined') {
        // 浏览器环境，使用fetch API
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });
            const responseData = await response.text();
            console.log('status code：', response.status);
            console.log('response data：', responseData);
            return {
                status: response.status,
                data: responseData
            };
        } catch (error) {
            console.error('浏览器环境发送请求失败:', error);
            throw error;
        }
    } else {
        // Node.js环境
        return new Promise((resolve, reject) => {
            const options = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                rejectUnauthorized: false // 忽略HTTPS证书验证
            };

            const req = https.request(url, options, (res) => {
                let responseData = '';
                res.on('data', (chunk) => {
                    responseData += chunk;
                });
                res.on('end', () => {
                    console.log('status code：', res.statusCode);
                    console.log('response data：', responseData);
                    resolve({
                        status: res.statusCode,
                        data: responseData
                    });
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            req.write(JSON.stringify(data));
            req.end();
        });
    }
}

async function sendMonitoringData(data) {
    try {
        console.log('sending pbi data:', data);
        
        // 检查运行环境
        if (typeof window !== 'undefined') {
            // 浏览器环境 - 使用fetch API
            console.log('浏览器环境：使用fetch API发送监控数据');
            
            if (axios && typeof axios.post === 'function') {
                // 在浏览器中，不使用httpsAgent（浏览器不支持）
                const response = await axios.post(url, data);
                console.log('status code：', response.status);
                console.log('response data：', response.data);
                return { success: true, message: '监控数据发送成功' };
            } else {
                console.error('浏览器环境中axios未正确初始化');
                return { success: false, message: '浏览器环境中axios未正确初始化' };
            }
        } else {
            // Node.js环境
            console.log('Node.js环境：使用axios或https模块发送监控数据');
            
            if (axios && typeof axios.post === 'function') {
                // 使用axios发送请求（仅在Node.js环境中使用httpsAgent）
                const agent = new https.Agent({ rejectUnauthorized: false });
                const response = await axios.post(url, data, { httpsAgent: agent });
                console.log('status code：', response.status);
                console.log('response data：', response.data);
                return { success: true, message: '监控数据发送成功' };
            } else {
                // 使用备用方法发送请求
                console.log('axios无效，使用Node.js内置https模块发送请求');
                const response = await sendWithNodeHttps(data);
                return { success: true, message: '监控数据发送成功(使用备用方法)' };
            }
        }
    } catch (error) {
        console.error('Error sending monitoring data:', error.message);
        console.error('Error details:', error);
        
        let errorMessage = '';
        if (error.response) {
            errorMessage = `服务器响应错误: ${error.response.status} ${JSON.stringify(error.response.data)}`;
            console.error('Response status:', error.response.status);
            console.error('Response data:', error.response.data);
        } else if (error.request || error.message.includes('Fetch请求失败')) {
            errorMessage = '未收到服务器响应，可能是网络问题、CORS限制或服务器不可用';
            console.error('No response received or fetch failed:', error.request || error.message);
        } else {
            errorMessage = `请求设置错误: ${error.message}`;
            console.error('Error setting up the request:', error.message);
        }
        return { success: false, message: errorMessage };
    }
}

// 模块导出 - 浏览器环境兼容
if (typeof module !== 'undefined' && module.exports) {
    // Node.js环境
    module.exports = {
        sendMonitoringData
    };
} else if (typeof window !== 'undefined') {
    // 浏览器环境，将函数添加到全局对象
    window.sendMonitoringData = sendMonitoringData;
}